package dtu.k12tpm.pbs.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.thoughtworks.xstream.XStream;

import dtu.k12tpm.pbs.contact.Contact;
import dtu.k12tpm.pbs.service.WebService;
import dtu.k12tpm.pbs.util.ContactProvider;

public class DetailSenderContactActivity extends MyActivity {
	private ArrayList<Contact>		items			= new ArrayList<Contact>();
	private ListView				lv;
	private ArrayAdapter<Contact>	aa;
	private boolean					items_modified	= false;
	ContactProvider					cp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("New Contacts");
		setContentView(R.layout.content_sender);
		lv = (ListView) findViewById(R.id.List);
		Bundle bundle = getIntent().getExtras();
		String id = (String) bundle.getString("id_package");
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
			items = WebService.getPakageContact(id);
			aa = new ArrayAdapter<Contact>(this, R.layout.item_contact_info, items) {

				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_contact_info, null);
					}

					Contact contact = items.get(position);
					if (contact != null) {
						TextView tvTopLeftInfo = (TextView) v.findViewById(R.id.tvTopLeftInfo);
						TextView tvTopRightInfo = (TextView) v.findViewById(R.id.tvTopRightInfo);
						TextView tvBottomRightInfo = (TextView) v.findViewById(R.id.tvBottomRightInfo);
						TextView tvBottomLeftInfo = (TextView) v.findViewById(R.id.tvBottomLeftInfo);
						CheckBox chkSelectContact = (CheckBox) v.findViewById(R.id.chkSelectContact);

						chkSelectContact.setChecked(contact.isChecked());

						HashMap<String, String> info = cp.getContactInfoToShow(contact);

						tvTopLeftInfo.setText(contact.getFirstName(info.get("DisplayName")));
						tvTopRightInfo.setText(contact.getLastName(info.get("DisplayName")));
						tvBottomRightInfo.setText(info.get("BottomRightInfo"));
						tvBottomLeftInfo.setText(info.get("BottomLeftInfo"));
					}
					return v;
				}
			};
		} catch (Exception e) {
			showMessageDialog("Exception", "DetailSenderContactActivity: " + e.getMessage());
		}
		lv.setAdapter(aa);
	}

	@Override
	public void onBackPressed() {
		Bundle bundle = getIntent().getExtras();
		String id = (String) bundle.getString("id_package");
		if (items.isEmpty()) {
			try {
				WebService.deleteSender(id);
			} catch (Exception e) {
				showMessageDialog("Exception", "Exception throwed when attemping delete an empty list");
			}
		}
		String xml_content = new XStream().toXML(items);
		if (items_modified)
			try {
				WebService.updateContentSender(xml_content, id);
			} catch (Exception e) {
				showMessageDialog("Exception", "Exception throwed when attemping update content send");
			}
		super.onBackPressed();
	}

	public void AddContactClick(View v) {

		boolean hasCheck = false;
		for (Contact contact : items) {
			if (contact.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			final ProgressDialog pd = showProgressDialog(null, "Please waiting...", false);
			synchronized (pd) {
				new AddContactThread(pd).start();
			}
		} else {
			showToast("Please choose any contacts");
		}
	}

	Handler	dataSetHandler	= new Handler();

	public void notifyDataSetChanged(final ProgressDialog pd) {
		dataSetHandler.post(new Runnable() {

			@Override
			public void run() {
				aa.notifyDataSetChanged();
				pd.dismiss();
			}
		});

	}

	public void setState(final ProgressDialog pd, final String msg) {
		dataSetHandler.post(new Runnable() {

			@Override
			public void run() {
				pd.setMessage("Saving '" + msg + "'");
			}
		});
	}

	class AddContactThread extends Thread {
		ProgressDialog	pd;

		public AddContactThread(ProgressDialog pd) {
			this.pd = pd;
		}

		public void run() {
			int length = items.size();
			for (int i = 0; i < length; i++) {
				final Contact contact = items.get(i);
				if (contact.isChecked()) {
					// Kiem tra trung
					if (cp.findContactWithName(contact.getDisplayName()) == 0) {
						setState(pd, contact.getDisplayName());
						cp.writeContact(contact);
						items.remove(i);
						items_modified = true;
						i--;
						length--;
					} else {
						dataSetHandler.post(new Runnable() {

							@Override
							public void run() {
								showToast("Contact '" + contact.getDisplayName() + "' has been existed");
							}
						});
					}
					Log.i("Size items", "" + items.size());
				}
			}
			notifyDataSet();
		}

		private void notifyDataSet() {
			if (items.isEmpty()) {
				try {
					Bundle bundle = getIntent().getExtras();
					String id = (String) bundle.getString("id_package");
					Log.i("Deleting", id);
					WebService.deleteSender(id);
					Log.i("Deleted", "Done");
					bundle.clear();
					Log.i("Bundle", "Cleared");
					finish();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				notifyDataSetChanged(pd);
			}
		}
	}

	public void deleteContact(View v) {
		boolean hasCheck = false;
		for (Contact contact : items) {
			if (contact.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			showConfirmDialog("Delete Confirm", "Are you sure you want to delete?", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					DetailSenderContactActivity.this.findViewById(R.id.cmdDeleteContact).setEnabled(false);
					for (int i = 0; i < items.size(); i++) {
						Contact contact = items.get(i);
						if (contact.isChecked()) {
							items.remove(i--);
							items_modified = true;
						}
						Log.i("Tracking array items", "size: " + items.size());
					}
					DetailSenderContactActivity.this.aa.notifyDataSetChanged();
					if (items.isEmpty()) {
						try {
							Bundle bundle = getIntent().getExtras();
							String id = (String) bundle.getString("id_package");
							Log.i("Connecting server", "Deleting sender with id " + id);
							WebService.deleteSender(id);
						} catch (Exception e) {
							showMessageDialog("Exception", "Exception throwed when attemping delete an empty list");
						}
						DetailSenderContactActivity.this.finish();
					} else {
						DetailSenderContactActivity.this.findViewById(R.id.cmdDeleteContact).setEnabled(true);
					}
				}
			});
		} else {
			showToast(R.string.msg_WhenDontSelectContact);
		}
	}

	public void contactCheckButtonClick(View v) {
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(((CheckBox) v).isChecked());
	}
}
